﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using AEM.Data;
using AEM.Data.BLL.Actions;
using Actions = AEM.Data.BLL.Actions;

namespace AEM
{
    /// <summary>
    /// LiftMonitoring.xaml 的交互逻辑
    /// </summary>
    public partial class LiftMonitoring : Window
    {
        public event EventHandler<EventArgs> HideEventHandler;
        private string liftnum = "";
        private string floor = "";
        private Data.Model.LiftInfo liftinfo = null;
        public LiftMonitoring()
        {
            InitializeComponent();
            this.TitleBar.MouseLeftButtonDown += new MouseButtonEventHandler(LiftMonitoring_MouseLeftButtonDown);
            this.btn_close.Click += new RoutedEventHandler(btn_close_Click);
            this.Loaded += new RoutedEventHandler(LiftMonitoring_Loaded);
            this.btn_status_locked.Click += new RoutedEventHandler(btn_status_locked_Click);
            this.btn_status_reset.Click += new RoutedEventHandler(btn_status_reset_Click);
            this.btn_UDF1.Click += new RoutedEventHandler(btn_UDF1_Click);
            this.btn_UDF2.Click += new RoutedEventHandler(btn_UDF2_Click);
            this.btn_UDF3.Click += new RoutedEventHandler(btn_UDF3_Click);

            this.btn_status_locked.Tag = true;//true时可锁梯,false时可解锁
            this.btn_UDF1.Tag = true;
            this.btn_UDF2.Tag = true;
            this.btn_UDF3.Tag = true;

            Actions.LiftInfo.LiftMonitoring = LiftMonitor;

        }

        void LiftMonitoring_Loaded(object sender, RoutedEventArgs e)
        {
            Data.Model.ClientConfig r = Data.DAL.ClientConfig.Search();
            if (null != r)
            {
                if (null != r.ElevatorOutput)
                {
                    List<string> tmp = r.ElevatorOutput.Split(',').ToList();
                    if (tmp.Count < 3) { tmp.AddRange((new string[] { "", "", "" })); }
                    if (!string.IsNullOrEmpty(tmp[0])) this.btn_UDF1.Content = tmp[0];
                    if (!string.IsNullOrEmpty(tmp[1])) this.btn_UDF2.Content = tmp[1];
                    if (!string.IsNullOrEmpty(tmp[2])) this.btn_UDF3.Content = tmp[2];
                }
                if (null != r.ElevatorInput)
                {
                    List<string> tmp = r.ElevatorInput.Split(',').ToList();
                    if (tmp.Count < 3) { tmp.AddRange((new string[] { "", "", "" })); }
                    if (!string.IsNullOrEmpty(tmp[0])) this.status_udf1.Text = tmp[0];
                    if (!string.IsNullOrEmpty(tmp[1])) this.status_udf2.Text = tmp[1];
                    if (!string.IsNullOrEmpty(tmp[2])) this.status_udf3.Text = tmp[2];
                }
            }

            CheckPower();

        }

        private void CheckPower()
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.UDF1))
                this.btn_UDF1.IsEnabled = false;
            else this.btn_UDF1.IsEnabled = true;
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.UDF2))
                this.btn_UDF2.IsEnabled = false;
            else this.btn_UDF2.IsEnabled = true;
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.UDF3))
                this.btn_UDF3.IsEnabled = false;
            else this.btn_UDF3.IsEnabled = true;
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.LockLift))
                this.btn_status_locked.IsEnabled = false;
            else this.btn_status_locked.IsEnabled = true;
        }

        void btn_UDF1_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.UDF1))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            Operate((bool)(sender as Button).Tag, "8");
        }

        private void Operate(bool type, string comm)
        {
            if (null != Actions.SerialPorts.Regulate && null != liftinfo)
                Actions.SerialPorts.Regulate.BeginInvoke(type,
                    liftinfo.LiftNum, liftinfo.LiftCOM, byte.Parse(comm, NumberStyles.HexNumber), 0, new AsyncCallback(Actions.SerialPorts.RegulateCallback), null);
        }

        void btn_UDF2_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.UDF2))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            Operate((bool)(sender as Button).Tag, "9");
        }

        void btn_UDF3_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.UDF3))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            Operate((bool)(sender as Button).Tag, "0A");
        }

        /// <summary>
        /// 锁梯
        /// </summary>
        void btn_status_locked_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.LockLift))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            Operate((bool)(sender as Button).Tag, "2");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ln">电梯编号</param>
        /// <param name="ld">电梯运行方向</param>
        /// <param name="ds">门状态,true开,false关</param>
        /// <param name="fn">当前楼层</param>
        /// <param name="ls">电梯状态</param>
        private void LiftMonitor(SerialDataEventArgs e)
        {
            if (Dispatcher.CheckAccess()) return;
            if (null == e || null == e.Data) return;
            if (this.liftnum != e.LiftNum.ToString()) return;
            bool ds = e.Data.DoorOpen;
            if (e.Data.DoorClose) ds = false;

            Dispatcher.Invoke(new Action(() =>
            {
                #region 运行方向/上行,下行
                if (e.Data.Rising)
                {
                    this.up_ring_status.Fill = new SolidColorBrush(Color.FromRgb(0xEF, 0xEF, 0xEF));
                }
                else
                {
                    this.up_ring_status.Fill = new SolidColorBrush(Color.FromRgb(0x4D, 0x4D, 0x4D));
                }
                if (e.Data.Descending)
                {
                    this.down_ring_status.Fill = new SolidColorBrush(Color.FromRgb(0xEF, 0xEF, 0xEF));
                }
                else
                {
                    this.down_ring_status.Fill = new SolidColorBrush(Color.FromRgb(0x4D, 0x4D, 0x4D));
                }
                #endregion
                #region 门运动
                bool isOpen = false;
                isOpen = e.Data.DoorClose ? false : true;
                isOpen = e.Data.DoorOpen;
                if (isOpen)
                {
                    if (this.door_left.Width == 39)
                    {
                        ((Storyboard)this.TryFindResource("DoorOpenStoryboard")).Begin();
                    }
                }
                else
                {
                    if (door_left.Width == 0)
                    {
                        ((Storyboard)this.TryFindResource("DoorCloseStoryboard")).Begin();
                    }
                }
                #endregion
                this.lift_floor.Content = e.FloorShow;
                #region 吊索运动
                string[] fs = this.floor.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                //cage_sling.Height  453
                double cageto = 453 * (fs.Length - e.Floor) / fs.Length;
                Storyboard s = new Storyboard();
                DoubleAnimation da = new DoubleAnimation(cageto, TimeSpan.FromSeconds(1));
                Storyboard.SetTargetProperty(da, new PropertyPath("Height"));
                s.Children.Add(da);
                s.Begin(this.cage_sling);
                #endregion
                #region 状态

                //this.faultcode.Text = e.StatusCode;
                //IEnumerable<string> fault = (from r in Config.dataBaseDataset.TableFaultDefinition
                //                             where r.FaultCode == e.StatusCode
                //                             select r.FaultName).Take(1);
                //if (fault.Count() > 0)
                //    this.faultname.Text = fault.ToArray<string>()[0];
                this.status_fault.IsOn = this.status_fault.IsOn ? true : e.Data.FaultLamp;
                this.status_overhaul.IsOn = e.Data.Overhaul;
                this.status_fire.IsOn = this.status_fire.IsOn ? true : e.Data.Fire;
                this.status_driver.IsOn = e.Data.Dirver;
                this.status_overload.IsOn = e.Data.OverLoad;
                this.status_standalone.IsOn = e.Data.StandAlone;
                this.status_outofservice.IsOn = e.Data.OutOfService;
                this.status_local.IsOn = e.Data.Local;
                this.status_remote.IsOn = e.Data.Remote;
                //this.status_eps.IsOn = e.Data.EPS;
                this.status_mainpower.IsOn = e.Data.MainPower;
                this.status_firereturn.IsOn = e.Data.FireReturn;
                this.status_cagealarm.IsOn = this.status_cagealarm.IsOn ? true : e.Data.CageAlarm;
                this.status_power.IsOn = e.Data.Power;
                this.status_converteralarm.IsOn = this.status_converteralarm.IsOn ? true : e.Data.ConverterAlarm;
                this.status_cagelocked.IsOn = e.Data.CageLocked;
                this.status_doorlocked.IsOn = e.Data.DoorLocked;
                this.status_locked.IsOn = e.Data.Locked;
                this.status_earthquake.IsOn = this.status_earthquake.IsOn ? true : e.Data.IsEarthquaked;
                this.status_peak.IsOn = e.Data.Peak;

                this.status_udf1.IsOn = e.Data.UDF1;
                this.status_udf2.IsOn = e.Data.UDF2;
                this.status_udf3.IsOn = e.Data.UDF3;
                #endregion

                this.btn_status_locked.Tag = !e.Data.RemoteLocked;
                if (e.Data.RemoteLocked)
                {
                    this.btn_status_locked.Content = (string)this.TryFindResource("Unlock");
                }
                else
                {
                    this.btn_status_locked.Content = (string)this.TryFindResource("LockUp");
                }
                this.isRemoteLocked.Visibility = e.Data.RemoteLocked ? Visibility.Visible : Visibility.Hidden;
                this.btn_UDF1.Tag = !e.Data.UDF1Return;
                this.isUDF1Return.Visibility = e.Data.UDF1Return ? Visibility.Visible : Visibility.Hidden;
                this.btn_UDF2.Tag = !e.Data.UDF2Return;
                this.isUDF2Return.Visibility = e.Data.UDF2Return ? Visibility.Visible : Visibility.Hidden;
                this.btn_UDF3.Tag = !e.Data.UDF3Return;
                this.isUDF3Return.Visibility = e.Data.UDF3Return ? Visibility.Visible : Visibility.Hidden;

            }));
        }

        void btn_status_reset_Click(object sender, RoutedEventArgs e)
        {
            this.status_fault.IsOn = false;
            this.status_fire.IsOn = false;
            this.status_cagealarm.IsOn = false;
            this.status_converteralarm.IsOn = false;
            this.status_earthquake.IsOn = false;

            if (null != Actions.LiftInfo.ResetAlarm)
                Actions.LiftInfo.ResetAlarm.Invoke();
            if (null != Log.AddOperation)
            {
                string log = "=StatusReset";// (string)System.Windows.Application.Current.TryFindResource("StatusReset");
                Log.AddOperation.BeginInvoke(log, new AsyncCallback(Log.AddOperationCallback), null);
            }
        }

        void btn_close_Click(object sender, RoutedEventArgs e)
        {
            if (null != HideEventHandler)
                HideEventHandler.Invoke(this, null);
            // this.Close();
        }

        private void sys_button_close_Click(object sender, RoutedEventArgs e)
        {
            if (null != HideEventHandler)
                HideEventHandler.Invoke(this, null);
            // this.Close();
        }
        private void sys_button_min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private static void OnLiftIDChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            if (args.NewValue != args.OldValue)
            {
                Data.Model.LiftInfo model = Data.DAL.LiftInfo.Select((int)args.NewValue);
                if (null == model) { (sender as LiftMonitoring).lift_name.Content = (sender as LiftMonitoring).TryFindResource("NoID") as string; return; }
                InitModelInfo(sender as LiftMonitoring, model);
            }
        }

        private static void InitModelInfo(LiftMonitoring m, Data.Model.LiftInfo r)//状态初始化
        {
            m.status_cagealarm.IsOn = false;
            m.status_cagelocked.IsOn = false;
            m.status_converteralarm.IsOn = false;
            m.status_doorlocked.IsOn = false;
            m.status_driver.IsOn = false;
            m.status_earthquake.IsOn = false;
            m.status_fault.IsOn = false;
            m.status_fire.IsOn = false;
            m.status_firereturn.IsOn = false;
            m.status_local.IsOn = false;
            m.status_locked.IsOn = false;
            m.status_mainpower.IsOn = false;
            m.status_outofservice.IsOn = false;
            m.status_overhaul.IsOn = false;
            m.status_overload.IsOn = false;
            m.status_peak.IsOn = false;
            m.status_power.IsOn = false;
            m.status_remote.IsOn = false;
            m.status_standalone.IsOn = false;
            m.status_udf1.IsOn = false;
            m.status_udf2.IsOn = false;
            m.status_udf3.IsOn = false;
            m.liftnum = r.LiftNum.ToString();
            m.liftinfo = r;
            m.floor = r.LiftActualFloor;
            m.lift_name.Content = r.ShortName + " -- " + r.LiftSite;
        }

        void LiftMonitoring_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        #region 以下注册属性
        /// <summary>
        /// 数据库内电梯信息ID
        /// </summary>
        public static readonly DependencyProperty LiftIDProperty =
            DependencyProperty.Register("LiftID", typeof(int), typeof(LiftMonitoring),
            new FrameworkPropertyMetadata(0, new PropertyChangedCallback(OnLiftIDChanged)));

        /// <summary>
        /// 数据库内电梯信息ID
        /// </summary>
        public int LiftID
        {
            get { return (int)GetValue(LiftIDProperty); }
            set { SetValue(LiftIDProperty, value); }
        }

        #endregion

    }
}
